/*
 * @Date: 2020-07-15 17:19:00
 * @LastEditTime: 2020-07-15 17:43:35
 * @Description: 查找组件
 * @FilePath: \vue\src\common\utilFindComs.js
 */ 



/**
 * 向上查找指定父级组件
 * @param context 当前实例上下文:this
 * @param componentName 组件名
 * @param componentNames
 * @returns {*}
 */
const findComsUp = function (context, componentName, componentNames) {
    if (typeof componentName === 'string') {
      componentNames = [componentName]
    } else {
      componentNames = componentName
    }
  
    let parent = context.$parent
    let name = parent.$options.name
    while (parent && (!name || componentNames.indexOf(name) < 0)) {
      parent = parent.$parent
      if (parent) name = parent.$options.name
    }
    return parent
  }
  
  /**
   * 向下查找指定子组件
   * @param context 当前实例上下文:this
   * @param componentName 组件名
   * @returns {*}
   */
  const findComsDown = function (context, componentName) {
    const childrens = context.$children
    let children = null
  
    if (childrens.length) {
      for (const child of childrens) {
        const name = child.$options.name
        if (name === componentName) {
          children = child
          break
        } else {
          children = findComsDown(child, componentName)
          if (children) break
        }
      }
    }
    return children
  }
  
  /**
   * 查找兄弟组件(同级组件)
   * @param componentName 组件name
   * @param eventName 方法或属性名
   * @param params 传参
   * @returns {*}
   */
  const findComsPeer = function (componentName, eventName, params){
    const parent = findComsUp(this, 'CreateOrderForm')
    const result = findComsDown(parent, componentName)
    if (eventName && (result[eventName] === undefined || result[eventName] === null)) {
      console.error(`组件${componentName}：中未定义 ${eventName} 方法或属性`)
    } else if (eventName in result) {
      Type.isFunction(result[eventName]) ? result[eventName](params) : result[eventName] = params
    }
    return result
  }


  export{
    findComsUp,
    findComsDown,
    findComsPeer
  }